<template>
  <div ref="pageBlock" class="planningCreateMain">
    <el-dialog
      v-if="imageResult.length != 0"
      class="create_plan_dialog"
      title="创建中"
      :visible.sync="dialogVisible"
      width="50%"
    >
      <div class="image_progress_group">
        <h1>策划文档构造</h1>
        <el-progress
          :stroke-width="16"
          :percentage="progressPercent"
        ></el-progress>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleBackList">返回列表</el-button>
        <el-button type="primary" @click="handleDetail"> 查看详情</el-button>
      </span>
    </el-dialog>
    <div class="anchor-wrapper">
      <anchor ref="anchor" :page-block="pageBlock" />
      <div v-if="formType == 'edit'">
        <el-button type="primary" @click="handleSave">保存</el-button>
        <el-button type="danger" @click="goback">取消</el-button>
      </div>
      <div v-else-if="formType == 'add'">
        <el-button type="primary" @click="handleSave">创建</el-button>
      </div>
    </div>

    <div data-section="基础信息" data-ismain data-for="form1"></div>
    <keep-alive>
      <planning-create-base-info ref="form1" :data="formDataMap.form1" />
    </keep-alive>

    <div data-section="产品图片" data-ismain data-for="form2"></div>
    <planning-create-image ref="form2" :data="formDataMap.form2" />
    <div data-section="文档信息" data-ismain data-for="form3"></div>
    <planning-create-file-list ref="form3" :data="formDataMap.form3" />

    <div v-if="formType == 'edit'">
      <el-button type="primary" @click="handleSave">保存</el-button>
      <el-button type="danger">取消</el-button>
    </div>
    <div v-else-if="formType == 'add'">
      <el-button type="primary" @click="handleSave">创建</el-button>
    </div>
  </div>
</template>
<script>
import PlanningCreateBaseInfo from "./PlanningCreateBaseInfo.vue";
import PlanningCreateImage from "./PlanningCreateImage.vue";
import PlanningCreateFileList from "./PlanningCreateFileList.vue";
import Anchor from "./anchor/index.vue";
import { postRequest } from "@/api/api";
import { getRequest } from "@/api/api";
import { uploadFileRequest } from "@/api/api";
export default {
  name: "PlanningCreateIndex",
  // 组件
  components: {
    PlanningCreateBaseInfo,
    PlanningCreateImage,
    PlanningCreateFileList,
    Anchor,
  },
  props: {
    formType: {
      type: String,
      default: "add",
    },
  },
  provide() {
    return {
      formType: this.formType,
    };
  },
  //data数据
  data() {
    return {
      progressPercent: 0,
      dialogVisible: false,
      fullscreenLoading: false,
      imageTest: "",
      params: {
        id: parseInt(this.$route.params.id),
      },
      colors: [
        { color: "#f56c6c", percentage: 20 },
        { color: "#e6a23c", percentage: 40 },
        { color: "red", percentage: 60 },
        { color: "#1989fa", percentage: 80 },
        { color: "green", percentage: 100 },
      ],
      count: "",
      pageBlock: null,
      formDataMap: {
        form1: {
          options: [
            {
              value: "新风",
              label: "新风",
            },
            {
              value: "制热",
              label: "制热",
            },
            {
              value: "智眠",
              label: "智眠",
            },
          ],
          brandOptions: [
            {
              value: "画时代",
              label: "画时代",
            },
          ],
          distribution_channel: [],
          func: [],
          channel_options: [],
          extraFunction: "",
        },
        form2: {
          imageList: [],
        },
        form3: {
          appearance_issue_state: "0",
          appearance_file_list: [],
          plan_file_list: [],
          plan_state: "0",
          name_state: "0",
          series_name_state: "0",
          shell_state: "0",
          prototype_state: "0",
          recommend_book_state: "0",
          recommend_meeting_state: "0",
          production_state: "0",
          market_state: "0",
        },
      },
      imageResult: {},
      fileResult: {},
    };
  },
  provide() {
    return {
      formType: this.formType,
    };
  },
  created() {
    // console.warn("create");
    // 根据页面类型获取数据
    if (~["edit", "detail"].findIndex((i) => i === this.formType)) {
      this.postPlanning();
    } else {
      let _this = this;
      let channelData = [];
      channelData = this.getDistributionChannelList();
      console.log(channelData);
      this.formDataMap.form1.channel_options = channelData;
    }
  },
  mounted() {
    this.pageBlock = this.$refs["pageBlock"];
    console.log("this", this);
  },
  methods: {
    check(data) {
      // console.log("data", data);
      if (data == "") {
        data = null;
        return data;
      } else {
        return data.split(",");
      }
    },
    reRender() {
      this.$nextTick(() => {
        this.$refs["anchor"].reRender();
      });
    },
    handleBackList() {
      this.$router.push({ path: "/planning_list" });
    },
    handleDetail() {
      this.$router.push({ path: "/planning_detail/" + this.id });
    },
    //编辑、详情页面获取产品策划详细数据
    postPlanning() {
      postRequest("/plan/plan_detail", this.params).then((res) => {
        let records = res.data.data;
        var _this = this;
        let formDataMap = this.resolveDataToMap(records);
        // console.log("postFormDataMap:", formDataMap);
        // formDataMap.form1.channel_options = this.getDistributionChannelList();
        _this.formDataMap = Object.assign(formDataMap);
      });
      // console.log("this.formDataMap:", this.formDataMap);
    },
    // 获取销售渠道列表
    getDistributionChannelList() {
      var channel_options = [];
      getRequest("/distribution_channel/list").then((res) => {
        let list = res.data.data;
        for (let i = 0; i < list.length; i++) {
          let children = [];
          if (list[i].children != null && list[i].children.length > 0) {
            for (let j = 0; j < list[i].children.length; j++) {
              children.push({
                label: list[i].children[j].name,
                value: list[i].children[j].name,
              });
            }
            channel_options.push({
              label: list[i].name,
              value: list[i].name,
              children: children,
            });
          } else {
            channel_options.push({
              label: list[i].name,
              value: list[i].name,
            });
          }
        }
      });
      return channel_options;
    },
    // 数据转换
    resolveDataToMap(data) {
      let base = process.env.API_HOST;
      for (let i = 0; i < data.pictureList.length; i++) {
        // console.log(base + data.pictureList[i].path);
        data.pictureList[i].url = base + data.pictureList[i].path;
      }

      let channelData = [];
      channelData = this.getDistributionChannelList();

      
      const form1 = {
        id: data.id,
        name: data.name,
        brand: data.brand,
        seriesName: data.seriesName,
        productCode: data.productCode,
        productModel: data.productModel,
        category: data.category,
        specification: data.specification,
        position: data.position,
        energyLevel: data.energyLevel,
        developmentPlatform: data.developmentPlatform,
        color: data.color,
        material: data.material,
        func: this.check(data.func),
        project_office: data.project_office,
        remote_leader: data.remote_leader,
        remote_director: data.remote_director,
        plan_leader: data.plan_leader,
        plan_director: data.plan_director,
        project_leader: data.project_leader,
        project_director: data.project_director,
        out_director: data.out_director,
        out_leader: data.out_leader,
        inside_director: data.inside_director,
        inside_leader: data.inside_leader,
        smart_leader: data.smart_leader,
        smart_director: data.smart_director,
        print_leader: data.print_leader,
        print_director: data.print_director,
        base: data.base,
        type: data.type,
        origin: data.origin,
        changePoint: data.changePoint,
        windType: data.windType,
        distribution_channel: data.distribution_channel.split(","),
        
        //级联选择器的model需要创建一个新数组来赋值。push似乎无法双向绑定。

        options: [
          {
            value: "新风",
            label: "新风",
          },
          {
            value: "制热",
            label: "制热",
          },
          {
            value: "智眠",
            label: "智眠",
          },
        ],
      };
      form1.channel_options = channelData;
      const form2 = {
        imageList: data.pictureList,
      };
      const form3 = {
        appearance_file_list: data.appearanceList,
        plan_file_list: data.schemeFileList,
        appearance_issue_time: data.appearance_issue_time,
        appearance_issue_state: data.appearance_issue_state,
        name_state: data.name_state,
        name_date: data.name_date,
        series_name_state: data.series_name_state,
        series_name_date: data.series_name_date,
        shell_state: data.shell_state,
        shell_date: data.shell_date,
        prototype_state: data.prototype_state,
        prototype_date: data.prototype_date,
        recommend_book_state: data.recommend_book_state,
        recommend_meeting_state: data.recommend_meeting_state,
        recommend_meeting_date: data.recommend_meeting_date,
        recommend_book_date: data.recommend_book_date,
        production_state: data.production_state,
        production_date: data.production_date,
        market_state: data.market_state,
        market_date: data.market_date,
        plan_state: data.plan_state,
        plan_date: data.plan_date,
      };
      return { form1, form2, form3 };
    },
    resolveDataToChannel(data) {
      const form1 = {
        channel_options: data,
      };
      const form2 = {};
      const form3 = {};
      return { form1, form2, form3 };
    },
    startDivi() {
      const TIME_COUNT = 5;
      if (!this.timer) {
        this.count = TIME_COUNT;
        this.timer = setInterval(() => {
          if (this.count > 0 && this.count <= TIME_COUNT) {
            this.count--;
          } else {
            clearInterval(this.timer);
            this.timer = null;
            this.$router.push({
              path: "/planning_list",
            });
          }
        }, 1000);
      }
    },
    goback() {
      this.$router.back();
    },
    // 表单上传
    handleSave() {
      var _this = this;
      let appearance_deleted_file_list =
        _this.$refs["form3"].appearance_deleted_file_list;

      let image_deleted_file_list =
        _this.$refs["form2"].image_deleted_file_list;
      let scheme_deleted_file_list =
        _this.$refs["form3"].scheme_deleted_file_list;
      _this.dialogVisible = true;
      const formKeys = Object.keys(_this.formDataMap);
      // console.log("formKeys", _this.formDataMap);
      const validResults = formKeys.map((formKey) =>
        this.$refs[formKey].validForm()
      );
      // console.log(this.$refs["form1"]);
      // 开始校验
      if (validResults.every((r) => r)) {
        const formData = new FormData();
        let fullFormData = {};

        formKeys.map((formKey) => {
          const partFormData = this.$refs[formKey].formData;

          // console.log("partFormData", partFormData);
          Object.assign(fullFormData, partFormData);
        });
        Object.keys(fullFormData).forEach((key) => {
          formData.append(key, fullFormData[key]);
        });

        // 校验结束
        formData.delete("imageList");
        if (fullFormData.imageList) {
          for (let i = 0; i < fullFormData.imageList.length; i++) {
            formData.append("imageList", fullFormData.imageList[i].raw);
          }
        }
        formData.delete("appearance_file_list");
        if (fullFormData.appearance_file_list) {
          for (let i = 0; i < fullFormData.appearance_file_list.length; i++) {
            formData.append(
              "appearance_file_list",
              fullFormData.appearance_file_list[i].raw
            );
          }
        }
        formData.delete("plan_file_list");
        if (fullFormData.plan_file_list) {
          for (let i = 0; i < fullFormData.plan_file_list.length; i++) {
            formData.append(
              "plan_file_list",
              fullFormData.plan_file_list[i].raw
            );
          }
        }
        let createTime = this.getNowFormatDate();
        let createId = this.global.createUserId;
        formData.append(
          "appearance_deleted_file_list",
          appearance_deleted_file_list
        );
        let currentDate = this.getNowFormatDate();
        formData.append("currentDate", currentDate);
        formData.append("image_deleted_file_list", image_deleted_file_list);
        formData.append("scheme_deleted_file_list", scheme_deleted_file_list);
        formData.append("createId", createId);
        formData.append("createDate", createTime);
        // 调试前端，中断数据传递至后端
        this.fullscreenLoading = true;
        let callback = (progress) => {
          console.log(progress);
          this.progressPercent = progress;
        };
        if (this.formType == "edit") {
          uploadFileRequest("/plan/update", formData, callback).then((resp) => {
            if (resp.status == 200) {
              this.fullscreenLoading = false;
              let planningId = resp.data.data.id;
               this.$message.success("更新成功");
              this.id = planningId;
            } else {
              this.$message.warning("更新出错了");
              this.fullscreenLoading = false;
            }
          });
        } else {
          this.fullscreenLoading = true;
          uploadFileRequest("/plan/insert", formData, callback).then((resp) => {
            if (resp.status == 200) {
              if (resp.data.code == 1000) {
                _this.$message({ type: "success", message: "创建成功" });
                let planningId = resp.data.data.id;
                this.id = planningId;
                // console.log("id:", planningId);
                // _this.imageResult = resp.data.data.pictureList;
                // console.log("imageResult", _this.imageResult);
                // for (let i = 0; i < resp.data.data.pictureList.length; i++) {
                //   if ((resp.data.data.pictureList[i].status = true)) {
                //     _this.imageResult[i].percentage = 100;
                //   } else {
                //     _this.imageResult[i].percentage = 50;
                //   }
                // }
                // this.startDivi();
                // let path = "/planning_list";
                // this.$router.push(path);
              } else {
                this.fullscreenLoading = false;
                this.$message({ type: "warning", message: resp.data.msg });
              }
            } else {
              this.fullscreenLoading = false;
              this.$message({ type: "error", message: "服务器连接失败" });
            }
          });
        }
      } else {
        this.$message.warning("校验未通过");
      }
    },
  },
};
</script>
<style scoped>
.planningCreateMain {
  position: relative;
  padding: 16px;
  margin-top: 20px;
  margin-bottom: 20px;
}
.anchor-wrapper {
  position: fixed;
  opacity: 0.6;
  right: 0;
  width: 220px;
  height: 300px;
  top: 30%;
  transform: translate(0, -50%);
}
div[data-section] {
  position: relative;
  text-align: left;
  font-size: 14px;
  font-weight: bold;
  padding: 14px 0;
  margin-left: 34px;
}
div[data-section]::before {
  content: attr(data-section);
}

div[data-ismain] {
  font-size: 16px;
  font-weight: bold;
  margin-left: -8px;
}
div[data-ismain] ::after {
  content: "";
  position: absolute;
  left: -16px;
  top: 14px;
  width: 4px;
  height: 16px;
  background: #5c658d;
  border-radius: 2px;
}
</style>